#ifndef XGE_UNITTEST_XTHREAD_H_
#define XGE_UNITTEST_XTHREAD_H_

#include "xge_common_config.h"
#include "xassert.h"
#include "xdebug.h"
#include "xbase_common.h"
#include "xthread.h"
#include "xthread_manager.h"
#include "xthread_delegate.h"
#include "xatexit_manager.h"
#include "xsys_log.h"
#include "xunit_test.h"
#include <stdio.h>

using xge::xge_internal::ThreadDelegate ;
using xge::xge_internal::ThreadHandlerPtr;
using xge::xge_internal::ThreadManager;
using xge::xge_internal::ThreadDelegatePtr;
using xge::xge_internal::AtExitManager;
using xge::xge_internal::SystemLog;

class MyThread: public ThreadDelegate {
public:

  virtual void ThreadMain() {
    for( size_t i = 0 ; i < 10000 ; ++i ) {
      printf(".");
    }
  }


  ~MyThread() {
    printf("delete MyThread!");
  }


};


// CreateXThread test
UNIT_TEST(ThreadUnitTest,Case1) {
  ThreadManager::Initialize();
  ThreadDelegatePtr delegate_ptr( new MyThread() );
  int ec;
  ThreadHandlerPtr thread_1 = ThreadManager::CreateXThread(
    &ec,
    delegate_ptr,
    _xT("MyThread"),
    "Thread1"
    );
  // Can not fail
  XASSERT( !thread_1.Null() && ec == ThreadManager::EC_OK );
  thread_1->Join();
  // Now there must be no thread here
  XASSERT( ThreadManager::GetAllocatedThreadSize() == 0 );
  ThreadHandlerPtr thread[5];
  const char_t * name[5] = {
    _xT("1"),_xT("2"),_xT("3"),_xT("4"),_xT("5")
  };
  for( size_t i = 0 ; i < 5 ; ++i ) {
    thread[i] = ThreadManager::CreateXThread(&ec,
      ThreadDelegatePtr( new MyThread() ),
      name[i],
      "xxx"
      );
    XASSERT( !thread[i].Null() );
    XASSERT( ec == ThreadManager::EC_OK );
    printf("%d\n",ThreadManager::GetAllocatedThreadSize());
  }
  for( size_t i = 0 ; i < 5 ; ++i ) {
    thread[i]->Kill();
    xge::TripleResult res = thread[i]->IsRunning();
    XASSERT( res.Failed() );
  }
  XASSERT( ThreadManager::GetAllocatedThreadSize() == 0 );
}





#endif // XTHREAD_BASE_TEST_H_